import axios from 'axios'

import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(function(config) {
  // 带token
  const token = store.getters.token

  config.headers.Authorization = 'Bearer ' + token

  return config
}, function(error) {
  return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use((response) => {
  // 将axios返回数据解一层壳
  const res = response.data

  const { message, success } = res
  console.log(message, success)

  if (!success) {
    Message.error(message)

    return Promise.reject(new Error(message))
  }
  return res
}, (error) => {
  // 处理token失效
  console.dir(error)

  if (error.response.status === 401 && error.response.data.code === 10002) {
    // 弹出错误信息
    Message.error(error.response.data.message)
    // 清空用户数据
    store.dispatch('user/logout')
    // 跳转到登录页
    router.push('/login')
  } else {
  // 处理其他错误
    console.dir(error)
    Message.error(error.message)
  }
  return Promise.reject(error)
})

export default service
